import { execSync } from 'child_process'
// import { promisify } from 'util'
import prompts from 'prompts'
import { red } from 'kolorist'
import ora from 'ora'

// const exec = promisify(childProcess.exec)
/**
 * 如果存在package.json 询问是否安装脚本
 */
export default async (targetPath: string): Promise<void> => {
  const userAgent = process.env.npm_config_user_agent ?? ''
  const packageManager = /pnpm/.test(userAgent)
    ? 'pnpm'
    : /yarn/.test(userAgent)
      ? 'yarn'
      : /bun/.test(userAgent)
        ? 'bun'
        : 'npm'

  const { install }: { install: boolean } = await prompts([
    {
      type: 'confirm',
      name: 'install',
      message: `Install dependencies with ${packageManager}?`,
      initial: true
    }
  ],
  {
    onCancel: () => {
      throw new Error(red('✖') + ' Operation cancelled')
    }
  })

  if (!install) return

  const spinner = ora(`Dependencies installing with ${packageManager}...`)
  try {
    execSync(`${packageManager} install`, { cwd: targetPath, stdio: 'inherit' })
    spinner.succeed('Dependencies installed.')
  } catch (error) {
    spinner.fail((error as Error).message)
  }
}
